package hnet

import (
	"bytes"
	"encoding/binary"
	"errors"
	"haruhi/hiface"
	"haruhi/utils"
)

// 封包拆包类实例，暂时不需要成员
type DataPack struct{}

// 封包拆包实例初始化方法
func NewDataPack() *DataPack {
	return &DataPack{}
}

// 获取包头长度方法
func (dp *DataPack) GetHeadLen() uint32 {
	// Id uint32 + DataLen uint32 = 8字节
	return 8
}

// 封包方法
func (dp *DataPack) Pack(msg hiface.IMessage) ([]byte, error) {
	dataBuff := bytes.NewBuffer([]byte{})

	// write dataLen
	if err := binary.Write(dataBuff, binary.LittleEndian, msg.GetDataLen()); err != nil {
		return nil, err
	}

	// write msgID
	if err := binary.Write(dataBuff, binary.LittleEndian, msg.GetMsgId()); err != nil {
		return nil, err
	}

	// write data
	if err := binary.Write(dataBuff, binary.LittleEndian, msg.GetData()); err != nil {
		return nil, err
	}

	return dataBuff.Bytes(), nil
}

// 拆包方法
func (dp *DataPack) Unpack(binaryData []byte) (hiface.IMessage, error) {
	dataBuff := bytes.NewBuffer(binaryData)

	msg := &Message{}

	if err := binary.Read(dataBuff, binary.LittleEndian, &msg.DataLen); err != nil {
		return nil, err
	}

	if err := binary.Read(dataBuff, binary.LittleEndian, &msg.Id); err != nil {
		return nil, err
	}

	if utils.GlobalObject.MaxPacketSize > 0 && msg.DataLen > utils.GlobalObject.MaxPacketSize {
		return nil, errors.New("too large msg data recieved")
	}

	return msg, nil
}
